package com.xu.cloud.common.api;

import com.xu.cloud.common.constant.HttpConstant;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * api 版本请求条件
 *
 * @author xuguan
 * @since 2025/3/10
 */
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {

    private final String apiVersion;

    public ApiVersionRequestCondition(String apiVersion) {
        this.apiVersion = apiVersion;
    }

    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition other) {
        // 方法优先级高于类
        return new ApiVersionRequestCondition(other.getApiVersion());
    }

    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest request) {
        final String requestURI = request.getRequestURI();
        final Pattern pattern = Pattern.compile(HttpConstant.API_VERSION_PATTERN);
        final Matcher matcher = pattern.matcher(requestURI);
        if (!matcher.find()) {
            return null;
        }
        final String apiVersion = matcher.group();
        // 路径版本高于配置的版本才匹配
        if (ApiVersionComparator.INSTANCE.compare(apiVersion, this.getApiVersion()) >= 0) {
            return this;
        }
        return null;
    }

    @Override
    public int compareTo(ApiVersionRequestCondition other, HttpServletRequest request) {
        // 多个匹配, 优先匹配版本号高的
        return ApiVersionComparator.INSTANCE.compare(other.getApiVersion(), this.getApiVersion());
    }

    public String getApiVersion() {
        return apiVersion;
    }

}
